package com.fastadmin.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fastadmin.config.security.annotation.AnonymousAccess;
import com.fastadmin.mapper.impl.CompanyMapper;
import com.fastadmin.pojo.Company;
import com.fastadmin.pojo.FastParam;
import com.xphsc.easyjdbc.page.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequiredArgsConstructor
@Slf4j
public class CompanyController extends BaseController {

    private final CompanyMapper companyMapper;

    @GetMapping("sys/company/index")
    public String index() {
        return "sys/company/index";
    }

    @GetMapping("sys/company/add")
    public String add() {
        return "sys/company/add";
    }

    @GetMapping("sys/company/edit")
    public String index(@RequestParam Long ids, Model model) {
        Company company = this.companyMapper.findById(ids);
        model.addAttribute("company", company);
        return "sys/company/edit";
    }

    @RequestMapping("sys/company/data")
    @ResponseBody
    public Object data(FastParam fastParam) {
        PageInfo<Company> pageInfo = this.companyMapper.findByFastParam(fastParam);
        return datagrid(pageInfo);
    }

    @RequestMapping("sys/company/del")
    @ResponseBody
    public Object del(String ids) {
        String[] split = StrUtil.split(ids, ",");
        for (String s : split) {
            companyMapper.deleteById(s);
        }
        return ok();
    }

    @RequestMapping("sys/company/save")
    @ResponseBody
    public Object save(Company company) {
        if (ObjectUtil.isNotNull(company.getId())) {
            //修改
            companyMapper.update(company);
        } else {
            //保存
            companyMapper.save(company);
        }
        return ok();
    }


    @RequestMapping(value = "sys/company/all",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @AnonymousAccess
    public Object all() {
        List<Company> list = this.companyMapper.findAll();
        return ok(list);
    }

    @RequestMapping(value = "sys/company/findById", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @AnonymousAccess
    public Object findById(Long id) {
        Company list = this.companyMapper.findById(id);
        return ok(list);
    }


}
